package com.peng.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peng.pojo.Order;
import com.peng.pojo.SeckillOrder;
import com.peng.pojo.User;
import com.peng.rabbitmq.MQSender;
import com.peng.service.GoodsService;
import com.peng.service.OrderService;
import com.peng.service.SeckillGoodsService;
import com.peng.service.SeckillOrderService;
import com.peng.utils.JsonUtil;
import com.peng.vo.GoodsVo;
import com.peng.vo.SeckillMessage;
import com.peng.vo.result.RespBean;
import com.peng.vo.result.RespBeanEnum;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/seckill")
public class SeckillController {
    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private SeckillOrderService seckillOrderService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private RedisScript<Long> redisScript;
    @Autowired
    private MQSender mqSender;
    private Map<Long,Boolean> EmptyStockMap=new HashMap<Long, Boolean>();
    /**
     * windows 714
     * linux 138
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping("/doSeckill")
    @ResponseBody
    public RespBean doSeckill(Model model, User user , Long goodsId){
        if (user == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        model.addAttribute("user",user);
        //判断库存
//        GoodsVo seckillGoods = goodsService.findGoodsVoByGoodsId(goodsId);
//        if (seckillGoods.getStockCount()<1){
//            model.addAttribute("errmsg","商品已被抢光");
//            return "secKillFail";
//        }
//        LambdaQueryWrapper<SeckillOrder> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SeckillOrder::getGoodsId,goodsId);
//        queryWrapper.eq(SeckillOrder::getUserId,user.getId());
//        SeckillOrder seckillOrder = seckillOrderService.getOne(queryWrapper);
//        if (seckillOrder!=null){
//            model.addAttribute("errmsg","请不要重复抢购");
//            return "secKillFail";
//        }
        //判断是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        if (seckillOrder != null) {
            model.addAttribute("errmsg", "该商品只允许购买一次");
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //内存标记，减少Redis的访问
        if (EmptyStockMap.get(goodsId)) {
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        Long stock = (Long) redisTemplate.execute(redisScript, Collections.singletonList("seckillGoods:" + goodsId), Collections.EMPTY_LIST);
        if (stock < 0) {
            EmptyStockMap.put(goodsId, true);
            valueOperations.increment("seckillGoods:" + goodsId);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        SeckillMessage seckillMessag = new SeckillMessage(user, goodsId);
        mqSender.sendSeckillMessage(JsonUtil.object2JsonStr(seckillMessag));
        return RespBean.success(0);

    }

    /**
     * 获取秒杀结果
     *
     * @param tUser
     * @param goodsId
     * @return orderId 成功 ；-1 秒杀失败 ；0 排队中
     * @author LiChao
     * @operation add
     * @date 7:04 下午 2022/3/8
     **/
    @ApiOperation("获取秒杀结果")
    @GetMapping("getResult")
    @ResponseBody
    public RespBean getResult(User tUser, Long goodsId) {
        if (tUser == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        Long orderId = seckillOrderService.getResult(tUser, goodsId);
        return RespBean.success(orderId);
    }


}
